package com.future.service.impl;

import com.future.cons.Const;
import com.future.service.TradeService;
import com.future.util.RedissionDistributedLock;
import com.future.vo.Stock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description:
 *
 * @author weiruibai.vendor
 * Date: 2022/9/20 16:19
 */

@Service
@Qualifier(value = "redisDistributeLockServiceImpl")
public class RedisDistributeLockServiceImpl extends CommonService implements TradeService {

    AtomicInteger atomicInteger = new AtomicInteger(0);

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisDistributeLockServiceImpl.class);
    @Autowired
    private RedissionDistributedLock redission;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public String lock() {
        return (String) redission.tryLok(Const.TICKET_SUM, () -> {
            Object oldTicketSum = redisTemplate.opsForValue().get(Const.TICKET_SUM);
            int ticket;
            if (oldTicketSum == null || (ticket = Integer.parseInt(oldTicketSum + "")) < 1) {
                Stock stock = select(1);
                if (null != stock && stock.getStock() >= 1) {
                    ticket = stock.getStock();
                } else {
                    LOGGER.error("票数为空，停止抢票");
                    return "";
                }
            }
            LOGGER.info("current thread {},第 {} 次获取锁且能更新数据库,剩余票数: {}", Thread.currentThread(), atomicInteger.incrementAndGet(), --ticket);
            redisTemplate.opsForValue().set(Const.TICKET_SUM, ticket);
            doDBUpdate(ticket);
            return "";
        });
    }

}
